package org.aplikator.client.local;

import com.github.gwtbootstrap.client.ui.*;
import com.github.gwtbootstrap.client.ui.constants.Alignment;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.github.gwtbootstrap.client.ui.constants.NavbarConstants;
import com.github.gwtbootstrap.client.ui.constants.NavbarPosition;
import com.github.gwtbootstrap.client.ui.resources.Bootstrap;
import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import org.aplikator.client.local.command.AplikatorActivityMapper;
import org.aplikator.client.local.command.WelcomeScreen;
import org.aplikator.client.local.panels.FluidNavbar;
import org.aplikator.client.local.panels.MenuPanel;
import org.aplikator.client.local.processes.ProcessInformations;
import org.aplikator.client.shared.data.ClientContext;
import org.aplikator.client.shared.descriptor.ApplicationDTO;
import org.aplikator.client.shared.rpc.AplikatorService;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jboss.errai.ioc.client.api.EntryPoint;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * Entry point class of Aplikator application (defines <code>onModuleLoad()</code> ).
 */
@EntryPoint
public class Aplikator {

    public interface AplikatorResources extends ClientBundle {
        public static final AplikatorResources INSTANCE = GWT.create(AplikatorResources.class);

        @Source("Aplikator.css")
        public AplikatorCss css();
    }

    public interface AplikatorCss extends CssResource {
        public String mainHeader();

        public String dirty();
    }

    private static final Logger LOG = Logger.getLogger(Aplikator.class.getName());

    @Inject
    private Caller<AplikatorService> aplikatorServiceInjected;

    public static Caller<AplikatorService> aplikatorService;

    public static ApplicationDTO application;

    static {
        AplikatorResources.INSTANCE.css().ensureInjected();
    }

    private final EventBus eventBus = new SimpleEventBus();
    @SuppressWarnings("deprecation")
    private final PlaceController placeController = new PlaceController(eventBus);

    private final AplikatorActivityMapper activityMapper = new AplikatorActivityMapper();


    public static final ClientContext clientContext = new ClientContext();

    final DockLayoutPanel mainPanel = new DockLayoutPanel(Unit.PX);
    final MenuPanel menuPanel = new MenuPanel();

    final SimplePanel headerHolder = new SimplePanel();

    Navbar headerPanel = new FluidNavbar();

    final SimpleLayoutPanel contents = new SimpleLayoutPanel();

    @Inject
    private WelcomeScreen welcomeScreen;
    private Place defaultPlace;
    private static TextBox search = new TextBox();
    

    public static TextBox getSearch() {
    	return search;
	}


	/**
     * Aplikator client entry point method.
     */

    @PostConstruct
    public final void onModuleLoad() {
        //RestClient.setJacksonMarshallingActive(true);
        GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
            public void onUncaughtException(Throwable e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
            }
        });
        aplikatorService = aplikatorServiceInjected;
        defaultPlace = welcomeScreen.getPlace();
        initInfrastructure();
        aplikatorService.call( new RemoteCallback<ApplicationDTO>() {
            @Override
            public void callback(ApplicationDTO resp) {
                application = resp;
                initPanels();
                menuPanel.setMenus(application.getMenus(), placeController, activityMapper);
                if (application.getDefaultActionToken()!=null){
                    placeController.goTo(activityMapper.getPlace(application.getDefaultActionToken()));
                }
            }
        }).getApplication();
    }


    private void initPanels() {

        headerPanel.add(new Brand(application.getBrand()));
        DropdownButton loginButton = new DropdownButton("Login");
        loginButton.addStyle(Alignment.RIGHT);
        
        //TODO: Change to configuration
        NavLink processes = new NavLink();
        processes.setText("Processes");
        processes.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
            	ProcessInformations pi = new ProcessInformations();
                pi.display();
            }
        });
        loginButton.add(processes);

        NavLink profile = new NavLink();
        profile.setText("Profil");
        profile.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
            }
        });
        loginButton.setIcon(IconType.USER);
        loginButton.add(profile);
        NavLink logout = new NavLink();
        logout.setText("Logout");
        logout.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                //Window.alert("PROFIL");
            }
        });
        loginButton.add(logout);

        Button menuButton = new Button("Hlavní menu", IconType.HOME);
        menuButton.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                menuPanel.setAnimation(true);
                menuPanel.show();
            }
        });
        //menuButton.setIcon(IconType.HOME);
        Nav nav = new Nav();
        nav.add(menuButton);
        headerPanel.add(nav);
        search.setPlaceholder("Search");
        search.addStyleName(NavbarConstants.NAVBAR_SEARCH);
		search.addStyleName(Bootstrap.search_query);
        
        Nav rightnav = new Nav();
        rightnav.add(loginButton);
        rightnav.add(search);

        rightnav.setAlignment(Alignment.RIGHT);
        headerPanel.add(rightnav);
        headerPanel.setPosition(NavbarPosition.TOP);
        //headerPanel.setStyleName(AplikatorResources.INSTANCE.css().mainHeader());
        headerHolder.add(headerPanel);
        if (application.isShowNavigation()){
            mainPanel.addNorth(headerHolder, 42);
        }
        mainPanel.add(contents);


        RootLayoutPanel.get().add(mainPanel);

    }

    @SuppressWarnings("deprecation")
    private void initInfrastructure() {
        ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
        activityManager.setDisplay(contents);

        PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(activityMapper);
        historyHandler.register(placeController, eventBus, defaultPlace);

        // Goes to the place represented on URL else default place
        historyHandler.handleCurrentHistory();
    }

}
